package website.lhc.commo.util;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

/**
 * @ProjectName: springboot
 * @Package: website.lhc.commo.util
 * @ClassName: DateUtil
 * @Author: lhc
 * @Description: 时间工具类
 * @Date: 2020/7/5 下午 10:37
 */
public class DateUtil {

    private static final String DEFAULT_DATE_TIME_FORMATTER = "yyy-MM-dd HH:mm:ss";
    private static final String DEFAULT_DATE_FORMATTER = "yyy-MM-dd";

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String now() {
        return getDateTime(LocalDateTime.now(), DEFAULT_DATE_TIME_FORMATTER);
    }

    /**
     * 通过指定格式获取当前时间
     *
     * @param pattern
     * @return
     */
    public static String nowWithPattern(String pattern) {
        return getDateTime(LocalDateTime.now(), pattern);
    }

    /**
     * @param localDateTime
     * @param pattern
     * @return
     */
    public static String getDateTime(LocalDateTime localDateTime, String pattern) {
        Assert.state(localDateTime != null, "[localDateTime]不可为空");
        Assert.hasLength(pattern, "[pattern]不可为空");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE);
        return localDateTime.format(formatter);
    }

    /**
     * @param localDate
     * @param pattern
     * @return
     */
    public static String getDate(LocalDate localDate, String pattern) {
        Assert.state(localDate != null, "[localDateTime]不可为空");
        Assert.hasLength(pattern, "[pattern]不可为空");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE);
        return localDate.format(formatter);
    }

    /**
     * @return
     */
    public static String getLocalDate() {
        return getDate(LocalDate.now(), DEFAULT_DATE_FORMATTER);
    }

    /**
     * @param pattern
     * @return
     */
    public static String getLocalDateWithPattern(String pattern) {
        return getDate(LocalDate.now(), pattern);
    }

    /**
     * 通过字符串时间得到LocalDateTime
     *
     * @param dateTime
     * @param pattern
     * @return
     */
    public static LocalDateTime getDateTime(String dateTime, String pattern) {
        Assert.hasLength(dateTime, "[dateTime]不可为空");
        Assert.hasLength(pattern, "[pattern]不可为空");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE);
        return LocalDateTime.parse(dateTime, formatter);
    }

    /**
     * 通过字符串时间得到LocalDate
     *
     * @param date
     * @param pattern
     * @return
     */
    public static LocalDate getDate(String date, String pattern) {
        Assert.hasLength(date, "[dateTime]不可为空");
        Assert.hasLength(pattern, "[pattern]不可为空");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE);
        return LocalDate.parse(date, formatter);
    }
}
